<!--
 * @Description: 简化版表格组件(Vue2) - 使用Element UI原生分页
-->
<template>
  <div class="simple-table" v-loading="exportLoading">
    <!-- 搜索区域 -->
    <el-row v-show="showSearch && searchList.length">
      <el-form ref="queryForm" :inline="true" :model="queryForm" @keyup.enter.native="getDataList">
        <el-form-item 
          v-for="({ type, name, field, multiple, selectList, startDate, endDate }, index) in searchList"
          :key="'search-' + index" 
          :label="name"
        >
          <!-- 输入框 -->
          <el-input 
            v-if="type === 'input'" 
            v-model="queryForm[field]" 
            :placeholder="'请输入' + name + '...'"
          />
          
          <!-- 日期选择器 -->
          <el-date-picker
            v-if="type === 'date'"
            v-model="queryForm[field]"
            type="date"
            :placeholder="'请选择' + name + '...'"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />

          <!-- 日期带时分秒选择器 -->
          <el-date-picker
            v-if="type === 'datetime'"
            v-model="queryForm[field]"
            type="datetime"
            :placeholder="'请选择' + name + '...'"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
          
          <!-- 月份选择器 -->
          <el-date-picker
            v-if="type === 'month'"
            v-model="queryForm[field]"
            type="month"
            :placeholder="'请选择' + name + '...'"
            format="yyyy-MM"
            value-format="yyyy-MM"
          />
          
          <!-- 日期范围选择器 -->
          <el-date-picker
            v-if="type === 'daterange'"
            unlink-panels
            v-model="queryForm[field]"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="(val) => changeDateRange(val, startDate, endDate)"
          />
          
          <!-- 下拉选择器 -->
          <el-select 
            v-if="type === 'select'" 
            v-model="queryForm[field]" 
            :multiple="multiple"
            :placeholder="'请选择' + name + '...'" 
            clearable
            @change="handleSelectChange"
          >
            <el-option 
              v-for="({ dictLabel, dictCode }, i) in selectList" 
              :key="'sel-' + i" 
              :label="dictLabel" 
              :value="dictCode"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch()">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 操作按钮区 -->
    <el-row v-if="btnList.length || needExport || needImport">
      <div class="btn-group">
        <el-button
          v-for="({ action, type, value }, i) in btnList"
          :key="i"
          :type="type || 'primary'"
          class="mr10"
          @click="handleClick(action, {})"
        >
          {{ value }}
        </el-button>
        
        <el-button 
          v-if="needImport" 
          type="primary" 
          @click="handleClick('import', {})"
        >
          导入
        </el-button>
        <el-button 
          type="primary" 
          @click="handleExport()"
        >
          导出
        </el-button>
      </div>
    </el-row>

    <!-- 表格描述 -->
    <div v-if="tableDesc" class="table-desc">{{ tableDesc }}</div>

    <!-- 表格主体 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :element-loading-text="loadingText"
      :data="dataList"
      :header-cell-style="tableStyle.headerCellStyle"
      :cell-style="tableStyle.cellStyle"
      @selection-change="handleSelectionChange"
    >
      <!-- 选择列 -->
      <el-table-column 
        v-if="selection" 
        type="selection" 
        width="50"
      ></el-table-column>
      
      <!-- 序号列 -->
      <el-table-column 
        label="序号" 
        type="index" 
        width="70"
        align="center"
      ></el-table-column>
      
      <!-- 数据列 -->
      <el-table-column 
        v-for="(item, i) in listColumns" 
        :key="i" 
        :label="item.title" 
        :width="item.width || getTagWidth(item)"
        :fit="false"
        show-overflow-tooltip
        align="center"
      >
        <template slot-scope="scope">
          <!-- 标签展示 -->
          <template v-if="item.tagDict">
            <el-tag 
              v-if="getTagLabel(item, scope.row)"
              :type="getTagType(item, scope.row) || ''"
            >
              {{ getTagLabel(item, scope.row) }}
            </el-tag>
          </template>
          
          <!-- HTML内容 -->
          <template v-else-if="item.type === 'html' && typeof item.html === 'function'">
            <div v-html="item.html(scope.row)"></div>
          </template>
          
          <!-- 按钮 -->
          <template v-else-if="item.type === 'btn'">
            <el-button 
              type="text" 
              @click="handleClick(item.action, scope.row)"
            >
              {{ item.buttonName || '操作' }}
            </el-button>
          </template>

          <template v-else-if="item.key.includes('.')">
            {{ getValueByPath(scope.row, item.key) }}
          </template>

          <!-- 默认展示 -->
          <template v-else>
            {{ renderCell(item, scope.row) }}
          </template>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column 
        v-if="actionArr.length" 
        align="center"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            v-for="({ action, value, hiddenList }, i) in actionArr"
            :key="i"
            v-show="filterShowBtn(scope.row, hiddenList)"
            type="text"
            @click="handleClick(action, scope.row)"
          >
            {{ value }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 - 使用Element UI原生分页组件 -->
    <div v-if="isPage" class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
// import { downBlobFile } from '@/utils/other';
import { Message } from 'element-ui';

export default {
  name: 'SimpleTable',
  props: {
    // 表格数据接口
    tableApi: {
      type: Function,
      default: () => Promise.resolve({ rows: [], total: 0 })
    },
    // 搜索配置
    searchList: {
      type: Array,
      default: () => []
    },
    searchQuery: {
      type: Object,
      default: () => {}
    },
    // 表格描述
    tableDesc: {
      type: String,
      default: ''
    },
    // 顶部按钮配置
    btnList: {
      type: Array,
      default: () => []
    },
    // 列配置
    listColumns: {
      type: Array,
      default: () => []
    },
    // 操作列配置
    actionArr: {
      type: Array,
      default: () => []
    },
    // 初始是否加载数据
    createdIsNeed: {
      type: Boolean,
      default: true
    },
    needImport: {
      type: Boolean,
      default: false
    },
    // 是否需要导出
    needExport: {
      type: Boolean,
      default: false
    },
    // 导出接口
    exportUrl: {
      type: String,
      default: ''
    },
    // 导出文件名
    exportName: {
      type: String,
      default: '导出数据'
    },
    // 必传参数
    mustQuery: {
      type: Object,
      default: () => ({})
    },
    // 是否显示选择框(checkbox/radio)
    selection: {
      type: String,
      default: ''
    },
    // 是否分页
    isPage: {
      type: Boolean,
      default: true
    },
    // 加载提示文本
    loadingText: {
      type: String,
      default: '加载中...'
    }
  },
  data() {
    return {
      // 搜索表单
      queryForm: {
        ...this.searchQuery
      },
      // 表格数据
      dataList: [],
      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 加载状态
      loading: false,
      // 导出加载状态
      exportLoading: false,
      // 是否显示搜索区
      showSearch: true,
      // 表格样式
      tableStyle: {
        headerCellStyle: {
          fontWeight: 'bold'
        },
        cellStyle: {}
      }
    };
  },
  watch: {
    searchQuery: {
      handler(newVal) {
        if (newVal) {
          this.queryForm = Object.assign({}, this.queryForm, newVal);
        }
      }
    },
    mustQuery: {
      deep: true,
      handler(newVal) {
        if (newVal) {
          this.getDataList();
        }
      }
    },
    tableApi:{
      immediate: true,
      handler(newVal) {
        if (newVal) {
          if (this.createdIsNeed) {
            this.getDataList();
          }
        }
      }
    }
  },
  created() {
    // if (this.createdIsNeed) {
    //   this.getDataList();
    // }
  },
  methods: {
    // 获取表格数据
    async getDataList() {
      this.loading = true;
      try {
        const params = {
          ...this.mustQuery,
          ...this.queryForm,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        };
        const res = await this.tableApi(params);
        this.dataList = res.rows || [];
        this.pagination.total = res.total || 0;
      } catch (err) {
        Message.error('获取数据失败');
      } finally {
        this.loading = false;
      }
    },

    handleSearch(){
      this.getDataList();
      this.$emit('handleSearch', this.queryForm);
    },
    // 重置搜索条件
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryForm = {};
      this.pagination.currentPage = 1;
      this.getDataList();
      this.$emit('handleReset');
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.pagination.currentPage = 1;
      this.getDataList();
    },

    // 页码改变
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.getDataList();
    },

    // 选择项改变
    handleSelectionChange(selection) {
      let result = selection;
      // 单选逻辑
      if (this.selection === 'radio' && selection.length > 1) {
        const last = selection.pop();
        selection.forEach(item => {
          this.$refs.tableRef.toggleRowSelection(item, false);
        });
        result = [last];
      }
      this.$emit('selection-change', result);
    },

    // 处理按钮点击
    handleClick(action, record) {
      this.$emit('handleClick', { action, record });
    },

    // 处理导出
   async handleExport() {
      try {
        const params = { ...this.mustQuery, ...this.queryForm };
        await this.download(
          this.exportUrl,
          params,
          `${this.exportName}.xlsx`
        );
        this.$message.success('导出成功');
      } catch (err) {
        this.$message.error('导出失败');
      } finally {
        this.exportLoading = false;
      }
    },

    // 日期范围处理
    changeDateRange(value, startDate, endDate) {
      if (startDate && endDate) {
        this.queryForm[startDate] = value ? value[0] : '';
        this.queryForm[endDate] = value ? value[1] : '';
      }
    },

    // 获取标签宽度
    getTagWidth(column) {
      return column.width || '';
    },

    // 获取标签类型
    getTagType(column, row) {
      const { tagDict, key } = column;
      if (!tagDict || !key) return '';
      const item = tagDict.find(t => t.value === row[key]);
      return item?.elTagType || '';
    },

    // 获取标签文本
    getTagLabel(column, row) {
      const { tagDict, key } = column;
      if (!tagDict || !key) return '';
      const item = tagDict.find(t => t.value === row[key]);
      return item?.label || row[key] || '';
    },

    // 渲染单元格内容
    renderCell(column, row) {
      if (typeof column.render === 'function') {
        return column.render(row[column.key], row);
      }
      return row[column.key] !== undefined ? row[column.key] : '暂无数据';
    },

    // 检查权限(简化版)
    checkAuth(auth) {
      // 实际项目中可根据权限系统实现
      return true;
    },

    // 检查按钮是否隐藏
    filterShowBtn(row, hiddenList){
      let showBtn = true;
      if (hiddenList) {
        hiddenList.forEach((hiddenItem) => {
          showBtn = hiddenItem.showTerm.includes(String(row[hiddenItem.fileId]));
        });
      }
      return showBtn;
    },

    getValueByPath(obj, path) {
      if (!path) {
        return;
      }
      return path.split('.').reduce((acc, part) => acc && acc[part], obj);
    },

    handleSelectChange(val){
      this.$emit('handleSelectChange', val);
    }
  }
};
</script>

<style scoped>
.simple-table {
  padding: 16px;
  background: #fff;
}

.btn-group {
  margin-bottom: 16px ;
}

.table-desc {
  margin: 8px 0;
  color: #666;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

::v-deep .el-form-item__content .el-select {
  width: 192px !important;
}

::v-deep .el-form-item__label {
  font-family: 'PingFangSC-Regular', 'PingFang SC', sans-serif;
  font-weight: 400;
  font-style: normal;
  color: #333333;
}

::v-deep .el-table--border {
  border: 1px solid #d4d7de !important;
}
</style>